package managers;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Servlet Filter implementation class LoginCheck
 */
public class LoginCheck implements Filter {

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hsRequest = (HttpServletRequest) request;
		String requestPath = hsRequest.getServletPath();
		System.out.println("LoginCheck: " + requestPath);
		//chain.doFilter(request, response);
	/* "/login") || requestPath.equals("/addUser.html") || requestPath.equals("/AddUser") ||
	requestPath.startsWith("/login") */
		if(requestPath.equals("/index.html") || requestPath.equals("/climat.html") || requestPath.equals("/toAllEvent.jsp") 
				|| requestPath.equals("/jquery.zweatherfeed.min.js") || requestPath.equals("/example_jquerytools.css") ||
				requestPath.equals("/bg.jpg") || requestPath.equals("/navigator.png") || requestPath.equals("/SerEvent")||
				requestPath.equals("/AccessPanel") || requestPath.equals("/AccessMenu")|| requestPath.equals("/login") ||
				requestPath.equals("/login/login.css")|| requestPath.equals("/addUser.html") || requestPath.equals("/addUser.jsp")
				|| requestPath.equals("/AddUser") || requestPath.equals("/AddUser2") || requestPath.equals("/VerificationAJAX")
				|| requestPath.equals("/ajax.jsp") || requestPath.equals("/tools.js") || requestPath.equals("/images/valid.gif")
				|| requestPath.equals("/images/invalid.gif") || requestPath.equals("/ShowEvent")
				|| requestPath.equals("/indexAdmin.html") || requestPath.equals("/loginAdmin") || requestPath.equals("/addAdmin.html")
				|| requestPath.equals("/AccessAdminPanel") || requestPath.equals("/AddAdmin"))
			chain.doFilter(request, response);	//don't require login
		else	//require login
			if(hsRequest.getSession(false) == null || hsRequest.getSession(false).getAttribute("id") == null){	//there is no session yet...
				System.out.println("LoginCheck: No session...");
				response.getWriter().print("Controlled requested page, there was no session.");
				//((HttpServletResponse) response).sendRedirect("/index.html"));
			}else{	//there is a session...
				System.out.println("LoginCheck: Session detected.");
				chain.doFilter(request, response);
			}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
